import { generateRoutes } from '/@/utils/menu';
import { router } from '/@/router';
import { getUserMenu } from '/@/api/index';

const state = {
  menuRoutes: [],
  noMenuRoutes: [],
};
const mutations = {
  setMenuRoutes(state, data) {
    state.menuRoutes = data;
  },
  setNoMenuRoutes(state, data) {
    state.noMenuRoutes = data;
  },
};
const actions = {
  async loadMenu({ commit, getters }) {
    //请求菜单
    const res = await getUserMenu();
    const { menu: menuRoutes, route: noMenuRoutes } = res.data;
    commit('setMenuRoutes', menuRoutes);
    commit('setNoMenuRoutes', noMenuRoutes);
    const routes = generateRoutes(getters.routeList);
    // routes.push({
    //   path: '/:pathMatch(.*)*',
    //   redirect: '/', //young 0518
    // });
    routes.forEach((item) => {
      router.addRoute(item);
    });
  },
};

const getters = {
  menus: (state) => {
    return state.menuRoutes;
  },
  routeList: (state) => {
    const routes = [...state.menuRoutes, ...state.noMenuRoutes];
    return routes;
  },
};

export default {
  state,
  mutations,
  actions,
  getters,
};
